﻿using System;
using System.Collections.Generic;
using System.Threading;
using ThrottledProcessing.SampleApplication.Domain;
using ThrottledProcessing.SampleApplication.Interfaces;

namespace ThrottledProcessing.SampleApplication.Services
{
    public class DocumentService : IDocumentService
    {
        private readonly ILoggingService loggingService;
        private readonly Dictionary<string, ContentItem> documentStore = new Dictionary<string, ContentItem>();

        public DocumentService(ILoggingService loggingService)
        {
            this.loggingService = loggingService;
        }

        public ContentItem GetDocument(string documentUrl)
        {
            loggingService.Debug(string.Format("Getting document from repository with url: {0}", documentUrl));
            return documentStore.ContainsKey(documentUrl) ? documentStore[documentUrl] : null;
        }

        public void StoreDocument(ContentItem document)
        {
            // Simulate latency
            Thread.Sleep(DateTime.Now.Millisecond*2);

            if (!documentStore.ContainsKey(document.Url))
            {
                loggingService.Debug(string.Format("Adding document to repository with url: {0}", document.Url));
                documentStore.Add(document.Url, document);
            }
            else
                loggingService.Info("Not adding document to repository because it is already indexed");
        }
    }
}